package com.bd.scm.module.device.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bd.scm.dao.mapper.device.StDeviceMapper;
import com.bd.scm.domain.dto.device.DeviceDto;
import com.bd.scm.domain.dto.device.DzStDeviceDto;
import com.bd.scm.domain.dto.device.GetDeviceDto;
import com.bd.scm.domain.dto.door.DoorDto;
import com.bd.scm.domain.models.device.DzStDevice;
import com.bd.scm.domain.models.device.JuserKqRecord;
import com.bd.scm.domain.models.device.ShowStDevice;
import com.bd.scm.domain.models.device.StDevice;
import com.bd.scm.module.device.service.StDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Mason
 * @since 2019-09-03
 */
@Service
public class StDeviceServiceImpl extends ServiceImpl<StDeviceMapper, StDevice> implements StDeviceService {

    @Autowired
    private StDeviceMapper stDeviceMapper;


    /**
     * @param doorDto 查询条件与门tree一样公用一个DTO
     * @return
     */
    @Override
    public IPage<StDevice> getStDeviceList(DoorDto doorDto) {
        Page<StDevice> page = new Page<StDevice>(doorDto.getCurrent(), doorDto.getPageSize());
        return this.stDeviceMapper.getStDeviceList(page, doorDto);
    }

    /**
     * 根据场所ID获取场所下设备数量.
     *
     * @param placeId
     * @return
     */
    @Override
    public Integer getDeviceCountByPlaceId(Long placeId) {
        return stDeviceMapper.getDeviceCountByPlaceId(placeId);
    }

    /**
     * 设备管理界面--获取设备列表.
     *
     * @param getDeviceDto 查询条件
     * @return page信息
     */
    @Override
    public IPage<ShowStDevice> getDevicePages(GetDeviceDto getDeviceDto) {
        Page<ShowStDevice> page = new Page<ShowStDevice>(getDeviceDto.getPageNo(), getDeviceDto.getPageSize());
        OrderItem orderItem = OrderItem.desc("devSbId");
        page = page.addOrder(orderItem);
        return this.stDeviceMapper.getDevicePages(page, getDeviceDto);
    }

    /**
     * 获取设备最大编号+1.
     *
     * @return 现有最大编号+1
     */
    @Override
    public String getMaxIdFromDevices() {
        String maxId = null;
        try {
            //拿到现有最大值
            maxId = stDeviceMapper.getMaxIdFromDevices();
            if (null == maxId) {
                throw new Exception("数据库异常");
            } else {
                //转为数字+1,
                Integer i = Integer.parseInt(maxId);
                i += 1;
                //再次转为字符串
                maxId = "00" + i;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return maxId;
    }

    /**
     * 新增设备.
     *
     * @param deviceDto 新增设备的信息.
     */
    @Override
    @Transactional
    public void saveDevice(DeviceDto deviceDto) {
        stDeviceMapper.insertDevice(deviceDto);
        stDeviceMapper.updateDeviceLbAndType(deviceDto);
        stDeviceMapper.insertDtDev(deviceDto);
        stDeviceMapper.insertWtDevLog(deviceDto);
        stDeviceMapper.insertStDevModule(deviceDto);
    }

    /**
     * 根据bh获取设备信息.
     *
     * @param deviceDto 含有bh
     * @return 设备信息
     */
    @Override
    public DeviceDto getDeviceByBh(DeviceDto deviceDto) {
        return stDeviceMapper.getDeviceByBh(deviceDto.getBh());
    }

    /**
     * 修改设备.
     *
     * @param deviceDto 修改设备的信息.
     */
    @Override
    public void editDevice(DeviceDto deviceDto) {
        stDeviceMapper.editDevice(deviceDto);
    }

    /**
     * 删除设备.
     *
     * @param deviceDto bh.
     */
    @Override
    @Transactional
    public void deleteDevice(DeviceDto deviceDto) {
        String bh = deviceDto.getBh();
        //以下操作，跟踪标准软件sql所得

        //1,执行dev_delete存储过程
        stDeviceMapper.doDevDelete(bh);
        //2,插入表jreal_nowcmd
        stDeviceMapper.insertJrealNowcmd(deviceDto);
        //3,更新st_device
        stDeviceMapper.updateDevLbFromStDevice(bh);
        //4,插入数据到st_dev_module_del
        //stDeviceMapper.insertStDevModuleDelByBh(bh);
        //5,删除st_dev_module中的相关记录
        stDeviceMapper.deleteStDevModuleByBh(bh);
        //6,插入数据到dt_dev_del
        //stDeviceMapper.insertdtDevDelByBh(bh);
        //7,删除 dt_dev中的相关数据
        stDeviceMapper.deleteDtDevByBh(bh);
        //8,删除 st_control中的相关数据
        stDeviceMapper.deleteStControlByBh(bh);
        //9,删除st_dcard 中的相关数据
        stDeviceMapper.deleteStDcardByBh(bh);
        //10,删除mj_door_rule中的相关记录
        stDeviceMapper.deleteMjDoorRuleByBh(bh);
        //11,插入操作记录到日志表wt_dev_log
        stDeviceMapper.insertDeleteDeviceWtDevLog(deviceDto);

    }

    // 大众考勤系统
    // 查询
    @Override
    public IPage<DzStDevice> getDzStDeviceList(Page<DzStDevice> page, DzStDeviceDto dzStDeviceDto) {
        dzStDeviceDto.setStartRow((int) ((page.getCurrent()-1) * page.getSize() + 1));
        dzStDeviceDto.setEndRow((int) (page.getCurrent() * page.getSize()));
        dzStDeviceDto.setTotalsize(0);
        List<DzStDevice> dzStDeviceList = this.stDeviceMapper.getDzStDeviceList(dzStDeviceDto);
        page.setRecords(dzStDeviceList);
        int dzStDeviceTotalsize = this.stDeviceMapper.getDzStDeviceTotalsize(dzStDeviceDto);
        page.setTotal(dzStDeviceTotalsize);
        return page;
    }

    // 添加
    @Override
    public synchronized String insertDzStDevice(DzStDeviceDto dzStDeviceDto) {
        String rt = null;
        String maxId = null;
        //拿到现有最大值
        maxId = stDeviceMapper.getMaxIdFromDzDevices();
        if (null == maxId) {
            maxId = "9000001";
        } else {
            maxId = maxId.substring(2);
            //转为数字+1,
            Integer i = Integer.parseInt(maxId);
            i += 1;
            int size = stringSize(i);
            if(size == 1){
                //再次转为字符串
                maxId = "900000" + i;
            }
            if(size == 2){
                //再次转为字符串
                maxId = "90000" + i;
            }
            if(size == 3){
                //再次转为字符串
                maxId = "9000" + i;
            }
            if(size == 4){
                //再次转为字符串
                maxId = "900" + i;
            }
            if(size == 5){
                //再次转为字符串
                maxId = "90" + i;
            }
        }
        dzStDeviceDto.setBh(maxId);
        int i = this.stDeviceMapper.insertDzStDevice(dzStDeviceDto);
        if(i <= 0){
            rt = "添加失败";
        }
        return rt;
    }

    final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
            99999999, 999999999, Integer.MAX_VALUE };

    // Requires positive x
    static int stringSize(int x) {
        for (int i=0; ; i++)
            if (x <= sizeTable[i])
                return i+1;
    }

    // 修改
    @Override
    public String updateDzStDevice(DzStDeviceDto dzStDeviceDto) {
        String rt = null;
        int i = this.stDeviceMapper.updateDzStDevice(dzStDeviceDto);
        if(i <= 0){
            rt = "修改失败";
        }
        return rt;
    }

    // 删除
    @Override
    public String deleteDzStDevice(DzStDeviceDto dzStDeviceDto) {
        String rt = null;
        int i = this.stDeviceMapper.deleteDzStDevice(dzStDeviceDto);
        if(i <= 0){
            rt = "删除失败";
        }
        return rt;
    }

    /**
     *
     * @param juserKqRecord
     * @return
     */
    @Override
    public String saveJuserKqRecord(JuserKqRecord juserKqRecord) {
        String rt = null;
        // 识别方式
        juserKqRecord.setJlogSytle("m");
        DzStDeviceDto dzStDeviceDto = new DzStDeviceDto();
        dzStDeviceDto.setPkSysUser(juserKqRecord.getJlogUserId());
        dzStDeviceDto.setDevSbId(String.valueOf(juserKqRecord.getMjDevid()));
        // 判断是否 根据考勤点获取当前员工是否有打卡权限
        int juserKqMakeDoc = this.stDeviceMapper.getJuserKqMakeDoc(dzStDeviceDto);
        if(juserKqMakeDoc<=0){
            rt = "没有打卡权限";
        }else{
            // 打卡数据保存
            this.stDeviceMapper.saveJuserKqRecord(juserKqRecord);
        }
        return rt;
    }

    /**
     * 手机端定位当天上下班是否已打卡接口开发，返回前端上班是否已打卡，下班是否已打卡
     * @param dzStDeviceDto
     * @return
     */
    @Override
    public List<JSONObject> getUserTtTaskCard(DzStDeviceDto dzStDeviceDto) {
        JSONObject a = new JSONObject();
        JSONObject b = new JSONObject();
        List<JSONObject> userTtTaskCard = this.stDeviceMapper.getUserTtTaskCard(dzStDeviceDto);
        if(userTtTaskCard.size()>0){
            if(userTtTaskCard.size() == 1){
                Integer jlogDir = userTtTaskCard.get(0).getInteger("jlogDir");
                if(jlogDir == 2){
                    a.put("jlogDir",1);
                    a.put("cut",0);
                    userTtTaskCard.add(a);
                }
                if(jlogDir == 1){
                    b.put("jlogDir",2);
                    b.put("cut",0);
                    userTtTaskCard.add(b);
                }
            }
        }else{
          a.put("jlogDir",1);
          a.put("cut",0);
          b.put("jlogDir",2);
          b.put("cut",0);
          userTtTaskCard.add(a);
          userTtTaskCard.add(b);
        }
        return userTtTaskCard;
    }

}
